for i, v in enumerate(nums): # 判断当前值是否和上一位值是否重复,重复的就跳过,目的是为了去除重复解 if i > 0and nums[i] == nums[i - 1]: continue
left = i + 1 right = size - 1
# 只要左指针没有超过右指针,那么就一直循环 while left < right: sum_value = v + nums[left] + nums[right] if sum_value > 0: # 和值大于0, 右指针需要左移 right -= 1 elif sum_value < 0: # 和值小于0, 左指针需要右移 left += 1 else: result.append([v, nums[left], nums[right]]) # 判断左边界和右边界是否和下一位值重复,目的是为了去除重复解 while left != right and nums[left] == nums[left + 1]: left += 1 while left != right and nums[right] == nums[right - 1]: right -= 1 # 最后左右指针各移动一步 right -= 1 left += 1 return result
functhreeSum(nums []int) [][]int { var result [][]int
iflen(nums) < 3{ return result }
size := len(nums) sort.Ints(nums)
for i, v:= range nums{ if i > 0 && nums[i] == nums[i-1]{ continue }
left := i +1 right := size - 1
for left < right{ sumValue := v + nums[left] + nums[right] if sumValue >0{ right -=1 }elseif sumValue < 0 { left += 1 }else{ result = append(result, []int{v, nums[left], nums[right]})
for left != right && nums[left] == nums[left+1]{ left += 1 } for left != right && nums[right] == nums[right-1]{ right -=1 } left +=1 right -=1 } } } return result }